package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.Auditor;
import csu.web.credit_bank.pojo.vo.CreditCertificationVo;
import csu.web.credit_bank.service.AuditorsService;
import csu.web.credit_bank.utils.JwtHelper;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auditors")

public class AuditorsController {

    @Autowired
    private AuditorsService auditorsService;
    @Autowired
    private JwtHelper jwtHelper; // 用于从JWT Token中提取审核员ID

    @PostMapping
    public Result<Auditor> createAuditor(@RequestBody Auditor auditor) {
        try {
            return Result.success("审核员创建成功", auditorsService.createAuditor(auditor));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping("/{userId}")
    public Result<Auditor> getAuditorById(@PathVariable String userId) {
        Auditor auditor = auditorsService.getAuditorById(userId);
        return auditor != null ? Result.success(auditor) : Result.failure("审核员未找到");
    }

    @GetMapping
    public Result<IPage<Auditor>> getAuditorList(@RequestParam(defaultValue = "1") int page,
                                                 @RequestParam(defaultValue = "10") int size) {
        return Result.success(auditorsService.page(new Page<>(page, size)));
    }

    @PutMapping("/{userId}")
    public Result<Auditor> updateAuditor(@PathVariable String userId, @RequestBody Auditor auditor) {
        auditor.setUserId(userId);
        Auditor updatedAuditor = auditorsService.updateAuditor(auditor);
        return updatedAuditor != null ? Result.success("审核员更新成功", updatedAuditor) : Result.failure("审核员更新失败");
    }

    @DeleteMapping("/{userId}")
    public Result<Void> deleteAuditor(@PathVariable String userId) {
        return auditorsService.deleteAuditor(userId) ? Result.success("审核员删除成功") : Result.failure("审核员删除失败");
    }

    /**
     * 获取待审核的学分认证申请列表
     * GET /auditors/certifications/pending?page=1&size=10
     * 只有审核员可以访问此接口，用于查看需要处理的申请。
     * @param page 页码 (默认为1)
     * @param size 每页数量 (默认为10)
     * @return 包含待审核学分认证申请的分页结果 (包含申请人用户名)
     */
    @GetMapping("/certifications/pending")
    // 此处修改：返回类型改为 IPage<CreditCertificationVo>
    public Result<IPage<CreditCertificationVo>> getPendingCertifications(@RequestParam(defaultValue = "1") int page,
                                                                         @RequestParam(defaultValue = "10") int size) {
        return auditorsService.getPendingCertifications(page, size);
    }

    /**
     * 审核学分认证申请
     * PUT /auditors/certifications/{certificationId}/audit
     * 审核员对特定的学分认证申请进行通过或拒绝操作。
     * @param certificationId 认证申请的ID
     * @param auditStatus 审核状态 (1: 通过, 2: 拒绝)
     * @param credits 授予的学分数量 (当 auditStatus 为 1 时必须提供，且为非负数)
     * @param token JWT token，从请求头中获取，用于提取当前审核员的ID
     * @param applicantUserId 申请人（学生）的用户ID，该参数将用于更新学生学分记录和汇总
     * @return 审核结果
     */
    @PutMapping("/certifications/{certificationId}/audit")
    public Result auditCertification(@PathVariable String certificationId,
                                     @RequestParam("auditStatus") int auditStatus,
                                     @RequestParam(value = "credits", required = false, defaultValue = "0") Integer credits, // 默认值为0，如果通过但未传学分，则为0
                                     @RequestHeader("token") String token,
                                     @RequestParam("applicantUserId") String applicantUserId) {
        // 从JWT Token中获取当前审核员的用户ID
        // JwtHelper.getUserId() 返回 Long 类型，但我们的用户ID（userId）在Pojo和数据库中是 String 类型
        // 因此需要进行类型转换
        String auditorId = String.valueOf(jwtHelper.getUserId(token));

        // 验证 auditorId 是否有效
        if (auditorId == null || "null".equals(auditorId)) { // String.valueOf(null) 会是 "null"
            return Result.failure("无法获取审核员信息，请重新登录");
        }
        // 调用服务层进行学分认证审核
        return auditorsService.auditCertification(certificationId, auditStatus, auditorId, credits, applicantUserId);
    }
    /**
     * 新增：获取待审核的**课程**学分认证申请列表
     * GET /auditors/course-certifications/pending?page=1&size=10
     * 只有审核员可以访问此接口，用于查看需要处理的课程认证申请。
     * @param page 页码 (默认为1)
     * @param size 每页数量 (默认为10)
     * @return 包含待审核课程学分认证申请的分页结果 (包含申请人用户名、课程名称、课程学分)
     */
    @GetMapping("/course-certifications/pending")
    public Result<IPage<CreditCertificationVo>> getPendingCourseCertifications(@RequestParam(defaultValue = "1") int page,
                                                                               @RequestParam(defaultValue = "10") int size) {
        return auditorsService.getPendingCourseCertifications(page, size);
    }
}
